/**************************************
? Jonas Raoni Soares Silva
? http://www.joninhas.ath.cx:666
**************************************/

/********************************************************
* REQUIRES http://www.jsfromhell.com/geral/event-listener
********************************************************/

MaskInput = function( fnome, m ){ //v1.0
	var f = document.getElementById(fnome);
	removeEvent(f, "keypress");
	removeEvent(f, "keyup");
	for( var i in ( !/^(.)\^(.*)$/.test( m ) && f.setAttribute( 'maxlength', m.length ), { keypress: 0, keyup: 1 } ) )
		addEvent( f, i, function( e ){
			var patterns = { "1": /[A-Z]/i, "2": /[0-9]/, "4": /[?-?]/i, "8": /./ }, rules = { "a": 3, "A": 7, "9": 2, "C":5, "c": 1, "*": 8 };
			function validChar( c, rule ){
				var r = rules[rule] || 0;
				for( var i = 1; i <= r; i<<=1 )
					if( r & i && patterns[i].test( c ) )
						break;
				return i <= r || c == rule;
			}
			var k, mC, r, c = String.fromCharCode( k = e.key ), l = f.value.length;
			( !k || k == 8 ? 1 : ( r = /^(.)\^(.*)$/.exec( m ) ) && ( r[0] = r[2].indexOf( c ) + 1 ) + 1 ? r[1] == "O" ? r[0] : r[1] == "E" ? !r[0] : validChar( c, r[1] ) || r[0] : ( l = ( f.value += m.substr( l, ( r = /[A|9|C|\*]/i.exec( m.substr( l ) ) ) ? r.index : l ) ).length ) < m.length && validChar( c, m.charAt( l ) ) ) || e.preventDefault();
		} );
};

MaskInputByObject = function( f, m ){ //v1.0
	removeEvent(f, "keypress");
	removeEvent(f, "keyup");
	for( var i in ( !/^(.)\^(.*)$/.test( m ) && f.setAttribute( 'maxlength', m.length ), { keypress: 0, keyup: 1 } ) )
		addEvent( f, i, function( e ){
			var patterns = { "1": /[A-Z]/i, "2": /[0-9]/, "4": /[?-?]/i, "8": /./ }, rules = { "a": 3, "A": 7, "9": 2, "C":5, "c": 1, "*": 8 };
			function validChar( c, rule ){
				var r = rules[rule] || 0;
				for( var i = 1; i <= r; i<<=1 )
					if( r & i && patterns[i].test( c ) )
						break;
				return i <= r || c == rule;
			}
			var k, mC, r, c = String.fromCharCode( k = e.key ), l = f.value.length;
			( !k || k == 8 ? 1 : ( r = /^(.)\^(.*)$/.exec( m ) ) && ( r[0] = r[2].indexOf( c ) + 1 ) + 1 ? r[1] == "O" ? r[0] : r[1] == "E" ? !r[0] : validChar( c, r[1] ) || r[0] : ( l = ( f.value += m.substr( l, ( r = /[A|9|C|\*]/i.exec( m.substr( l ) ) ) ? r.index : l ) ).length ) < m.length && validChar( c, m.charAt( l ) ) ) || e.preventDefault();
		} );
};
/*
MaskInput(field: HTMLInputElement, mask: String): void 
Adiciona m?scara a um campo. 
fieldcampo que vai receber a m?scara 
maskm?scara que ser? aplicada 
Regras
regras padr?es
--------------------------------
a = A-Z e 0-9
A = A-Z, acentos e 0-9
9 = 0-9
C = A-Z e acentos
c = A-Z
* = qualquer coisa

regras especiais
--------------------------------
E = (Except) exce??o
O = (Only) somente



cria??o de m?scaras
================================

m?scara simples
---------------
nesse tipo de m?scara o usu?rio pode digitar no m?ximo o mesmo
n?mero de caracteres q a m?scara cont?m
ex:
telefone = (99)9999-9999
placa de carro = ccc-9999

m?scara especial "regra^exce??es"
--------------------------------
esse tipo de m?scara ? composto por 2 partes, separadas pelo "^",
o lado esquerdo especifica a regra e o direito as exce??es para a regra selecionada.
ex:
9^abc = a regra ? aceitar somente n?meros "9" e a exce??o s?o os caracteres a, b e c
c^123 = aceita somente caracteres de a-z e a exce??o s?o os n?meros 1, 2 e 3

exce??es
--------
E^abc: aceita qualquer coisa, menos os a, b e c
O^123: s? permite os caracteres 1, 2 e 3

Exemplos
--------
var f = document.atendentesEditForm;
MaskInput( f.data, "99/99/9999" );
MaskInput( f.etc, "Cc99-*C" );
MaskInput( f.except, "E^abc" );
MaskInput( f.only, "O^abc" );
MaskInput( f.letra, "C^" );
MaskInput( f.letra2, "C^ " );
MaskInput( f.numero, "9^abc" );
*/
/*
**************************************
* Event Listener Function v1.2       *
* Autor: Carlos R. L. Rodrigues      *
**************************************
*/

addEvent = function(o, e, f){
	var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [o[e]] : []), a;
	r[r.length] = f, o[e] = function(e){
		try{
			(e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
			e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
			e.target || (e.target = e.srcElement || null);
			e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
		}catch(f){}
		for(f in r)
		a = r[f], a.call ? a.call(o, e) : (o._ = a, o._(e), o._ = null);
		e = null;
	}
};
removeEvent = function(o, e, f){
	for(var i in e = o["_on" + e])
		if(e[i] == f)
			return delete e[i];
	return false;
};

removeEvent = function(o, e){
	for(var i in e = o["_on" + e])
		delete e[i];
	return false;
};

function numberFormat(input, force) {
    if ( (event.keyCode > 47 && event.keyCode < 58) || String.fromCharCode(event.keyCode) == "-" || force ) {
    	var num = input.value;
		while (num.indexOf(".") > 0 || num.indexOf(",") > 0) {
		    num = num.replace(".", "");
		    num = num.replace(",", "");
	    }
    	if (num.length < input.maxLength) {
	        if (num.length >= 2) {
	        	if (!force) {
		        	if (String.fromCharCode(event.keyCode) == "-") {
		        		if (num.substr(0, 1) == "-") {
		        			num = num.substr(1, num.length);
		        		} else {
				    		num = "-" + num;
				    	}
				    } else {
				    	num += String.fromCharCode(event.keyCode);
				    }
			    }
			    num = num.substr(0, num.length - 2) + "." + num.substr(num.length - 2, 2);
	        	num = formatCurrency(num);
	    	} else {
	    		num += String.fromCharCode(event.keyCode);
	    	}
	    	input.value = num;
	    }
    }
    event.returnValue = false;
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) {
		num = "0";
	}
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num * 100 + 0.50000000001);
	cents = num % 100;
	num = Math.floor(num / 100).toString();
	if ( cents < 10) {
		cents = "0" + cents;
	}
	for (var i = 0; i < Math.floor((num.length - ( 1 + i )) / 3); i++) {
		num = num.substring(0, num.length - (4 * i + 3)) + '.' + num.substring(num.length - (4 * i + 3));
	}
	return (((sign) ? '' : '-') + num + ',' + cents);
}

function hourFormat(input, force) {
    if ( (event.keyCode > 47 && event.keyCode < 58) || String.fromCharCode(event.keyCode) == ":" || force ) {
    	var num = input.value;
		while (num.indexOf(":") > 0) {
		    num = num.replace(":", "");
	    }
    	if (num.length < input.maxLength) {
	        if (num.length >= 2) {
	        	if (!force) {
		        	if (String.fromCharCode(event.keyCode) == "-") {
		        		if (num.substr(0, 1) == "-") {
		        			num = num.substr(1, num.length);
		        		} else {
				    		num = "-" + num;
				    	}
				    } else {
				    	num += String.fromCharCode(event.keyCode);
				    }
			    }
			    num = num.substr(0, num.length - 2) + "." + num.substr(num.length - 2, 2);
	        	num = formatCurrency(num);
	    	} else {
	    		num += String.fromCharCode(event.keyCode);
	    	}
	    	input.value = num;
	    }
    }
    event.returnValue = false;
}

/*
**************************************
* String.isCPF Function v1.0         *
* Autor: Carlos R. L. Rodrigues      *
**************************************
*/
function checkCpf(input){
    var c = input.value;
    var ok = true;
    if((c = c.replace(/[^\d]/g,"").split("")).length != 11) ok = false;
    if(new RegExp("^" + c[0] + "{11}$").test(c.join(""))) ok = false;
    for(var s = 10, n = 0, i = 0; s >= 2; n += c[i++] * s--);
    if(c[9] != (((n %= 11) < 2) ? 0 : 11 - n)) ok = false;
    for(var s = 11, n = 0, i = 0; s >= 2; n += c[i++] * s--);
    if(c[10] != (((n %= 11) < 2) ? 0 : 11 - n)) ok = false;
    if (!ok) {
    	alert("CPF invalido!");
    	input.focus();
    }
}